#coding:utf-8

import sys
from application import application
from datetime import datetime
import os
from tornado.ioloop import IOLoop
from apscheduler.schedulers.tornado import TornadoScheduler
from apscheduler.triggers.interval import IntervalTrigger
from redlock.lock import RedLock
from jobs import manager

PORT = '5680'
if os.getcwd() not in sys.path:
    sys.path.append(os.getcwd())

def tick():
    lock = RedLock("yyj:python_lock_python", connection_details=[
            {"host": "10.1.91.22", "port": 6379, "db": 0, "socket_timeout": 0.2}], ttl=60000)
    locked = lock.acquire()
    print('This job starts at: %s' % datetime.now())
    if locked:
        manager.doall()
    #print("%s" % locked)
    print('This job ends at: %s' % datetime.now())
    lock.release()

if __name__ == "__main__":
    if len(sys.argv) > 1:
        PORT = sys.argv[1]
    application.listen(PORT)

    print('Development server is running at http://127.0.0.1:%s/' % PORT)
    print('Press Ctrl+{0} to quit the server'.format('Break' if os.name == 'nt' else 'C'))
    
    #scheduler = TornadoScheduler()
    #trigger = IntervalTrigger(seconds=15)
    #scheduler.add_job(tick,trigger)
    #scheduler.start()
    
    try:
        IOLoop.instance().start()
    except (KeyboardInterrupt, SystemExit):
        pass
